<template>
  <page-container>
    <app-card>
      <template #header>
        数据筛选
      </template>
      <el-form
        :inline="true"
        ref="form"
        size="mini"
        :model="listParams"
        :disabled="listLoading"
        @submit.prevent="handleQuery"
      >
        <el-form-item label="文章分类">
          <el-select
            v-model="listParams.pid"
            placeholder="请选择"
            clearable
            @clear="listParams.pid = 0"
            @change="loadList"
          >
            <el-option
              label="全部"
              :value="0"
            />
            <el-option
              v-for="cate in categorys"
              :key="cate.title"
              :label="cate.title"
              :value="cate.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章搜索">
          <el-input
            v-model="listParams.title"
            clearable
            placeholder="请输入身份昵称"
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                native-type="submit"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </app-card>
    <app-card>
      <template #header>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddArticle"
        >
          添加文章
        </el-button>
      </template>
      <el-table
        :data="list"
        stripe
        style="width: 100%"
        v-loading="listLoading"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="55"
        />
        <el-table-column
          prop="image_input"
          label="文章图片"
          width="80"
        >
          <template #default="{row}">
            <el-image
              v-for="(image, index) in row.image_input"
              :key="image"
              :src="image"
              @click="preview(row.image_input, Number(index))"
              fit="contain"
              style="width: 38px; height: 38px"
            >
              <template #error>
                <div class="image-slot">
                  <i
                    class="el-icon-picture"
                    style="font-size: 28px; margin: 5px; color: rgb(219, 219, 219);"
                  />
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="文章名称"
          width="180"
        />
        <el-table-column
          prop="store_name"
          label="关联商品"
          min-width="220"
        />
        <el-table-column
          prop="visit"
          label="浏览量"
          width="80"
        />
        <el-table-column
          prop="add_time"
          label="时间"
          width="160"
          sortable
          :formatter="dateFormat"
        />
        <el-table-column
          label="操作"
          fixed="right"
          width="160"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="text"
              @click="handleUpdate(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              @click="toggleRelationProduct(scope.row)"
            >
              {{ scope.row.storeInfo && scope.row.storeInfo.id ? '取消': '' }}关联
            </el-button>
            <el-popconfirm
              title="确认删除吗？"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button type="text">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <app-pagination
        v-model:page="listParams.page"
        v-model:limit="listParams.limit"
        :list-count="listCount"
        :load-list="loadList"
        :disabled="listLoading"
      />
    </app-card>
    <app-product-select
      :model-value="selectFormVisible"
      :selected="setRelationProductArticle"
      @cancel="selectFormVisible = false"
    />
  </page-container>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue'
import { getArticles, deleteArticle, relationProductArticle, getArticleCategorys, unrelationProductArticle } from '@/api/article'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Article, ArticleCategory, ArticleQuery } from '@/api/types/article'
import { usePreview } from '@/compositions/preview'
import dayjs from 'dayjs'
import type { Product } from '@/api/types/product'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()

const preview = usePreview()

const list = ref<Article[]>([]) // 列表数据
const listCount = ref(0)
const listLoading = ref(true)
const listParams: ArticleQuery = reactive({ // 列表数据查询参数
  page: 1, // 当前页码
  limit: 10, // 每页大小
  pid: route.query.pid ? route.query.pid.toString() : 0,
  title: ''
})

const articleId = ref<number | null | undefined>(null)

onMounted(() => {
  Promise.all([loadCategorys(), loadList()])
})

const loadList = async () => {
  listLoading.value = true
  const data = await getArticles(listParams).finally(() => {
    listLoading.value = false
  })
  list.value = data.list
  listCount.value = data.count
}
const categorys = ref<ArticleCategory[]>()
const loadCategorys = async () => {
  const data = await getArticleCategorys({})
  categorys.value = data.list
}
const handleQuery = async () => {
  listParams.page = 1 // 查询默认从第1页开始
  loadList()
}

const handleDelete = async (id: number) => {
  await deleteArticle(id)
  ElMessage.success('删除成功')
  loadList()
}

const handleUpdate = (id: number) => {
  router.push({
    name: 'article-edit',
    params: {
      id
    }
  })
}

const handleAddArticle = () => {
  router.push({
    name: 'article-add'
  })
}

const selectFormVisible = ref(false)

const toggleRelationProduct = (article: Article) => {
  articleId.value = article.id
  if (article.storeInfo && article.storeInfo.id) {
    ElMessageBox.confirm(
      'null',
      '取消关联',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // center: true,
        message: h('div', null, [
          h('p', null, '确定要取消关联吗？'),
          h('p', null, '取消关联后将无法恢复，请谨慎操作！')
        ])
      }
    )
      .then(async () => {
        if (articleId.value) {
          // todo: 错误处理
          await unrelationProductArticle(articleId.value)
          ElMessage({
            type: 'success',
            message: '取消关联成功'
          })
          loadList()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作'
        })
      })
      .finally(() => {
        articleId.value = null
      })
  } else {
    // 打开选择商品对话框
    selectFormVisible.value = true
  }
}

const setRelationProductArticle = async (product: Product) => {
  if (articleId.value) {
    await relationProductArticle(articleId.value, product.id)
    ElMessage({
      type: 'success',
      message: '关联成功'
    })
    loadList()
    articleId.value = null
    selectFormVisible.value = false
  }
}

const dateFormat = (row: Article, column: any) => {
  if (column.property === 'add_time') {
    return dayjs.unix(row.add_time).format('YYYY-MM-DD  HH:mm:ss')
  } else {
    return '-'
  }
}
</script>

<style lang="scss" scoped></style>
